package com.cenwangkeji.resident.presenter.activity;

import com.cenwangkeji.resident.model.Constant;
import com.cenwangkeji.resident.model.OkHttpUtils;
import com.cenwangkeji.resident.model.bean.LoginBean;
import com.google.gson.Gson;
import com.lws.basic.persenter.ObserverOnNext;
import com.lws.basic.utils.common.GsonUtils;
import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.RxUtils;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;

/**
 * @松 on 2019/10/28 11:05
 * 登陆逻辑
 */
public class LoginPresenter {
    private  I mI;

    public LoginPresenter(I i) {
        mI = i;
    }

    public void login(final String phone, final String pass){
        Observable.create(new ObservableOnSubscribe<LoginBean>() {
            @Override
            public void subscribe(ObservableEmitter<LoginBean> emitter) throws Exception {
                Map<Object,Object> map = new HashMap<>();
                map.put( "username",phone);
                map.put( "password",pass);
                map.put( "mark",3);
                JSONObject jsonObject = new JSONObject(map);
                String json = OkHttpUtils.post(jsonObject.toString(), Constant.login);
                MyLogger.i(json);
                Gson gson = GsonUtils.getInstance();
                emitter.onNext(gson.fromJson(json, LoginBean.class ));
            }
        }).compose(RxUtils.<LoginBean>io_main()).subscribe(new ObserverOnNext<LoginBean>() {
            @Override
            public void onNext(LoginBean loginBean) {
                 if (mI != null){
                     mI.loginSuccess(loginBean);
                 }
            }
        });
    }

    public interface I{
        void loginSuccess(LoginBean bean);
    }
}
